<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>node-large-file-upload</title>
</head>

<body>
    <input type="file" name="" id="file">
    <script>
        const file = document.querySelector("#file");
        const chunksFun = (file, size = 1024 * 1024 * 10) => {
            const chunks = []//[blob blob blob]
            for (let i = 0; i < file.size; i += size) {
                chunks.push(file.slice(i, i + size))
            }
            return chunks;
        }
        const uploadFiles = (chunks) => {
            //1.批量上传 promise.all[请求，请求...]
            //2.formData 方式上传 file标识 hash 索引
            const list = []
            for (let i = 0; i < chunks.length; i++) {
                const formData = new FormData();
                formData.append("index", i)
                formData.append("filename", "写真")
                formData.append("file", chunks[i])//一定要写在最后面
                list.push(fetch("http://localhost:3000/upload", {
                    method: 'POST',
                    body: formData
                }))
            }
            Promise.all(list).then((res) => {
                console.log('上传成功');
                //通知后端合并文件
                fetch("http://localhost:3000/merge", {
                    method: 'POST', headers: {
                        "Content-Type": 'application/json'
                    }, body: JSON.stringify({
                        filename: '写真'
                    })
                }).then((res) => { })
            })
        }
        file.addEventListener("change", (e) => {
            let file = e.target.files[0];//file对象 底层是继承blob 需要调用slice切割 6m
            const chunks = chunksFun(file)
            uploadFiles(chunks)
            console.log('chunks: ', chunks);
        })
    </script>
</body>

</html>